package com.sxtyxt.online.me;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sxtyxt.entity.Address;
import com.sxtyxt.entity.City;
import com.sxtyxt.entity.ResultVo;
import com.sxtyxt.online.ActBase;
import com.sxtyxt.online.R;
import com.sxtyxt.online.SystemConst;
import com.sxtyxt.online.SystemEnv;
import com.sxtyxt.util.GsonUtil;
import com.sxtyxt.util.TextUtil;
import com.sxtyxt.volley.LoadingDialogResultListenerImpl;
import com.sxtyxt.volley.URL;
import com.sxtyxt.volley.VolleyUtils;
import com.sxtyxt.widget.FloatingDialog;
import com.sxtyxt.widget.wheel.OnWheelChangedListener;
import com.sxtyxt.widget.wheel.OnWheelScrollListener;
import com.sxtyxt.widget.wheel.WheelView;
import com.sxtyxt.widget.wheel.adapter.MyCityAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 新建或者修改地址页面
 * Created by General on 15/8/12.
 */
public class ActModifyAddress extends ActBase implements View.OnClickListener, OnWheelChangedListener, OnWheelScrollListener {
    //所在地区布局
    LinearLayout layoutDistrict;
    //所在地区
    private TextView txtDistrict;
    //用户名
    private EditText etxtUserName;
    //手机号
    private EditText etxtMobile;
    //座机电话
    private EditText etxtTelPhone;
    //邮政编码
    private EditText etxtCode;
    //详细地址
    private EditText etxtAddress;

    //地址实体
    private Address address;
    //地址Id
    private String addressId = "-1";
    //保存地址按钮
    private Button btnSave;
    @Override
    protected int getLayoutId() {
        return R.layout.modify_address;
    }

    @Override
    protected boolean isShouldHideInput() {
        return false;
    }

    @Override
    protected void initUI() {
        super.initUI();
        address = (Address) getIntent().getSerializableExtra("address");
        txtDistrict = (TextView) findViewById(R.id.txt_district);
        layoutDistrict = (LinearLayout) findViewById(R.id.layout_district);
        layoutDistrict.setOnClickListener(this);
        btnSave = (Button) findViewById(R.id.btn_save);
        btnSave.setOnClickListener(this);
        etxtUserName = (EditText) findViewById(R.id.etxt_username);
        etxtMobile = (EditText) findViewById(R.id.etxt_mobile);
        etxtTelPhone = (EditText) findViewById(R.id.etxt_tel);
        etxtCode = (EditText) findViewById(R.id.etxt_code);
        etxtAddress = (EditText) findViewById(R.id.etxt_address);
        if(SystemEnv.getAddress()!=null&&SystemEnv.getAddress().size()>0){
            provinces = SystemEnv.getAddress();
            initPickerView();
        }else{
            getCity();
        }
        if (address != null) {
            addressId = address.getAddressId();
            provinceId = address.getProvinceId();
            cityId = address.getCityId();
            areaId = address.getAreaId();
            txtDistrict.setText(getUnNullString(address.getAreaInfo(), ""));
            etxtAddress.setText(getUnNullString(address.getAddress(), ""));
            etxtAddress.setSelection(etxtUserName.getText().length());

            etxtMobile.setText(getUnNullString(address.getMobPhone(), ""));
            etxtMobile.setSelection(etxtUserName.getText().length());

            etxtTelPhone.setText(getUnNullString(address.getTelPhone(), ""));
            etxtTelPhone.setSelection(etxtTelPhone.getText().length());

            etxtCode.setText(getUnNullString(address.getZipCode(), ""));
            etxtCode.setSelection(etxtUserName.getText().length());

            etxtUserName.setText(getUnNullString(address.getTrueName(), ""));
            etxtUserName.setSelection(etxtUserName.getText().length());

        }


       /* final LinearLayout layout = (LinearLayout) findViewById(R.id.layout_main);
        layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = layout.getRootView().getHeight() - layout.getHeight();
                if (heightDiff > 100) {
                    btnSave.setVisibility(View.GONE);
                } else {
                    btnSave.setVisibility(View.VISIBLE);
                }
            }
        });*/
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_district:
                if (cityDialog != null) {
                    cityDialog.show();
                }
                break;

            case R.id.btn_save:
                if (checkIsRight()) {
                    submitAddress();
                }
                break;

        }
    }

    private boolean checkIsRight() {
        if (TextUtils.isEmpty(getStringByUI(etxtUserName))) {
            doToast("收货人姓名不能为空");
            return false;
        }
        if (!TextUtil.isMobileNumber(getStringByUI(etxtMobile))) {
            doToast("手机号不合法");
            return false;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtCode))) {
            doToast("邮编不能为为空");
            return false;
        }
        if (getStringByUI(etxtCode).length() != 6) {
            doToast("邮编不合法");
            return false;
        }
        if (TextUtils.isEmpty(provinceId) || TextUtils.isEmpty(cityId)) {
            doToast("所在地区不能为空");
            return false;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtAddress))) {
            doToast("地址不能为空");
            return false;
        }
//        if (!TextUtil.isTelephoneNumber(getStringByUI(etxtTelPhone))) {
//            doToast("座机电话不合法");
//            return false;
//        }


        return true;

    }


    /*******
     * 第一步：选择城市代码开始
     ******/

    private WheelView provinceWheel;
    private List<City> provinces;
    private MyCityAdapter provinceAdapter = null;

    private WheelView cityWheel;
    private List<City> citys;
    private MyCityAdapter cityAdapter = null;

    private WheelView districtWheel;
    private List<City> districts;
    private MyCityAdapter districtAdapter = null;

    private int cityIndex = 0;
    private int provinceIndex = 0;
    private FloatingDialog cityDialog;

    private String cityId, areaId, provinceId;

    private void initPickerView() {
        if(cityDialog==null){
            cityDialog = new FloatingDialog(this, R.style.dialogAnim_Wheel, Gravity.BOTTOM);
            cityDialog.setContentView(R.layout.comm_city_picker);
        }
        Button btnCancel = (Button) cityDialog.findViewById(R.id.btn_picker_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cityDialog.dismiss();
            }
        });
        Button btnOK = (Button) cityDialog.findViewById(R.id.btn_picker_ok);
        btnOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cityDialog.dismiss();
                provinceId = (String) provinceAdapter.getItemTag(provinceWheel.getCurrentItem());
                cityId = (String) cityAdapter.getItemTag(cityWheel.getCurrentItem());
                areaId = (String) districtAdapter.getItemTag(districtWheel.getCurrentItem());
                txtDistrict.setText(getWheelText(11) + "," + getWheelText(12) + "," + getWheelText(13));
            }
        });
        provinceWheel = (WheelView) cityDialog.findViewById(R.id.picker_province);
        cityWheel = (WheelView) cityDialog.findViewById(R.id.picker_city);
        districtWheel = (WheelView) cityDialog.findViewById(R.id.picker_district);
        provinceWheel.addChangingListener(this);
        provinceWheel.addScrollingListener(this);
        cityWheel.addChangingListener(this);
        cityWheel.addScrollingListener(this);
        provinceAdapter = new MyCityAdapter(this, provinces);
        cityAdapter = new MyCityAdapter(this, citys);
        districtAdapter = new MyCityAdapter(this, districts);
        provinceWheel.setViewAdapter(provinceAdapter);
        cityWheel.setViewAdapter(cityAdapter);
        districtWheel.setViewAdapter(districtAdapter);


        updateCityPicker(cityWheel, 0);
        updateDistrictPicker(districtWheel, 0);


    }

    private void updateCityPicker(WheelView wheel, int index) {
        if(provinces!=null && provinces.size()>0){
            citys = provinces.get(index).getChildern();
        }else{
            citys=new ArrayList<>();
        }

        cityAdapter = new MyCityAdapter(this, citys);
        cityWheel.setViewAdapter(cityAdapter);
        cityWheel.setCurrentItem(0);

        updateDistrictPicker(districtWheel, 0);

    }

    private void updateDistrictPicker(WheelView wheel, int index) {
        if(citys!=null && citys.size() >0){
            districts = citys.get(index).getChildern();
        }else{
            districts =new ArrayList<>();
        }

        districtAdapter = new MyCityAdapter(this, districts);
        districtWheel.setViewAdapter(districtAdapter);
        districtWheel.setCurrentItem(0);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        switch (wheel.getId()) {
            case R.id.picker_city:
                cityIndex = newValue;
                break;
            case R.id.picker_province:
                provinceIndex = newValue;
                break;
            case R.id.picker_district:
                break;
            default:
                break;
        }
    }

    @Override
    public void onScrollingStarted(WheelView wheel) {

    }

    @Override
    public void onScrollingFinished(WheelView wheel) {
        switch (wheel.getId()) {
            case R.id.picker_province:
                updateCityPicker(cityWheel, provinceIndex);
                break;
            case R.id.picker_city:
                updateDistrictPicker(districtWheel, cityIndex);
                break;
            default:
                break;
        }
    }

    private String getWheelText(int type) {
        String text = "";
        switch (type) {
            case 11:// 省份
                text = provinceAdapter.getItemText(
                        provinceWheel.getCurrentItem()).toString();
                break;
            case 12:// 市
                text = cityAdapter.getItemText(cityWheel.getCurrentItem())
                        .toString();
                break;
            case 13:// 区、县
                text = districtAdapter.getItemText(
                        districtWheel.getCurrentItem()).toString();
                break;
            default:
                break;
        }

        return text;
    }

    private void getCity() {
        VolleyUtils.requestService(SystemConst.GET_CITY_URL, null, new LoadingDialogResultListenerImpl(this, "正在加载数据") {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                CityVO vo = GsonUtil.deser(response, CityVO.class);
                if (vo == null) {
                    return;
                }
                if (vo.getResult() == 1) {
                    if (vo.getList() != null && vo.getList().size() > 0) {
                        provinces = vo.getList();
                        initPickerView();
                        SystemEnv.saveAddress(provinces);
                    }
                } else {
                    doToast(vo.getMsg());
                }
            }
            @Override
            public void onError() {
                super.onError();
            }
        });
    }

    class CityVO extends ResultVo<City> {

    }


    private void submitAddress() {
        VolleyUtils.requestService(SystemConst.SAVE_ADDRESS_URL,
                URL.saveAddress(addressId, getStringByUI(etxtMobile), getStringByUI(etxtTelPhone), getStringByUI(etxtAddress),
                        getStringByUI(txtDistrict), cityId, areaId,
                        getStringByUI(etxtUserName), getLoginUserId(),
                        getStringByUI(etxtCode), provinceId),
                new LoadingDialogResultListenerImpl(this, "正在提交数据") {
                    @Override
                    public void onSuccess(String response) {
                        super.onSuccess(response);
                        ResultVo<?> vo = GsonUtil.deser(response, ResultVo.class);
                        if (vo == null) {
                            return;
                        }
                        if (vo.getResult() == 1) {
                            doToast(vo.getMsg());
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            doToast(vo.getMsg());
                        }

                    }

                    @Override
                    public void onError() {
                        super.onError();
                    }
                });
    }


}
